<template>
  <el-dialog
    v-model="visible"
    title="批量更新任务"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-form :model="formData" label-width="120px" ref="formRef">
      <el-alert type="info" :closable="false" style="margin-bottom: 20px">
        已选择 {{ selectedTasks.length }} 个任务
      </el-alert>

      <el-form-item label="调度开关">
        <el-switch v-model="formData.updates.schedule_enabled" />
        <div class="form-tip">开启后任务将按计划执行</div>
      </el-form-item>

      <el-form-item label="Cron表达式" v-if="formData.updates.schedule_enabled">
        <el-input
          v-model="formData.updates.cron_expression"
          placeholder="例如: 0 30 10 * * ?"
        />
        <div class="form-tip">需要同时启用调度开关</div>
      </el-form-item>

      <el-form-item label="任务权重">
        <el-input-number
          v-model="formData.updates.weight"
          :min="0"
          :max="10"
          :step="0.1"
          :precision="1"
          style="width: 100%"
        />
        <div class="form-tip">权重范围: 0-10，数值越大优先级越高</div>
      </el-form-item>

      <el-form-item label="任务类型">
        <el-select
          v-model="formData.updates.task_type"
          placeholder="请选择任务类型"
          style="width: 100%"
          clearable
        >
          <el-option label="标准任务" value="standard" />
          <el-option label="自定义任务" value="custom" />
          <el-option label="系统任务" value="system" />
        </el-select>
      </el-form-item>

      <el-form-item label="任务描述">
        <el-input
          v-model="formData.updates.description"
          type="textarea"
          :rows="3"
          placeholder="请输入任务描述"
        />
      </el-form-item>
    </el-form>

    <!-- 批量更新结果 -->
    <div v-if="batchResult" class="batch-result">
      <el-alert
        :type="batchResult.failed_count === 0 ? 'success' : 'warning'"
        :closable="false"
        style="margin-bottom: 20px"
      >
        <template #title>
          <div>
            <div style="margin-bottom: 8px">
              {{ getBatchResultTitle() }}
            </div>
            <div style="font-size: 14px">
              成功: {{ batchResult.success_count }} / 失败:
              {{ batchResult.failed_count }} / 总计:
              {{ batchResult.total_count }}
            </div>
          </div>
        </template>
      </el-alert>

      <DynamicTable
        :data="batchResult.results || []"
        :columns="resultColumns"
        :loading="false"
        border
        :show-pagination="false"
        :show-toolbar="false"
      >
        <template #status="{ row }">
          <el-tag
            :type="row.status === 'success' ? 'success' : 'danger'"
            size="small"
          >
            {{ row.status === "success" ? "成功" : "失败" }}
          </el-tag>
        </template>
      </DynamicTable>
    </div>

    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button
        type="primary"
        :loading="updating"
        @click="handleConfirm"
        :disabled="!hasUpdates"
      >
        确定更新
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import DynamicTable from "@/components/DynamicTable/index.vue";
import type { TableColumn } from "@/components/DynamicTable/types";
import { batchUpdateTasks } from "../../../servers";

const props = defineProps({
  modelValue: { type: Boolean, default: false },
  selectedTasks: { type: Array, default: () => [] },
});

const emit = defineEmits<{
  (e: "update:modelValue", value: boolean): void;
  (e: "confirm", result: any): void;
}>();

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value),
});

const formRef = ref();
const updating = ref(false);
const batchResult = ref<any>(null);

const formData = ref({
  updates: {
    schedule_enabled: undefined as boolean | undefined,
    weight: undefined as number | undefined,
    description: undefined as string | undefined,
    task_type: undefined as "standard" | "custom" | "system" | undefined,
    cron_expression: undefined as string | undefined,
  },
  updated_by: "admin",
});

// 检查是否有更新项
const hasUpdates = computed(() => {
  return Object.values(formData.value.updates).some(
    (value) => value !== undefined && value !== null && value !== ""
  );
});

// 监听弹窗打开，重置表单
watch(visible, (newVal) => {
  if (newVal) {
    formData.value = {
      updates: {
        schedule_enabled: undefined,
        weight: undefined,
        description: undefined,
        task_type: undefined,
        cron_expression: undefined,
      },
      updated_by: "admin",
    };
    batchResult.value = null;
  }
});

// 结果表格列配置
const resultColumns: TableColumn[] = [
  {
    label: "任务ID",
    prop: "task_id",
    width: 100,
    align: "center",
  },
  {
    label: "状态",
    prop: "status",
    width: 100,
    align: "center",
    slot: "status",
  },
  {
    label: "消息",
    prop: "message",
    minWidth: 300,
  },
];

// 获取批量更新结果标题
const getBatchResultTitle = () => {
  if (!batchResult.value) return "";
  if (batchResult.value.failed_count === 0) {
    return `批量更新成功 (${batchResult.value.success_count}个)`;
  }
  return `部分更新成功 (${batchResult.value.success_count}/${batchResult.value.total_count})`;
};

// 确认更新
const handleConfirm = async () => {
  if (!hasUpdates.value) {
    ElMessage.warning("请至少选择一个要更新的字段");
    return;
  }

  if (props.selectedTasks.length === 0) {
    ElMessage.warning("请先选择要更新的任务");
    return;
  }

  // 构建更新对象，只包含有值的字段
  const updates: any = {};
  if (formData.value.updates.schedule_enabled !== undefined) {
    updates.schedule_enabled = formData.value.updates.schedule_enabled;
  }
  if (formData.value.updates.weight !== undefined) {
    updates.weight = formData.value.updates.weight;
  }
  if (formData.value.updates.description !== undefined) {
    updates.description = formData.value.updates.description;
  }
  if (formData.value.updates.task_type !== undefined) {
    updates.task_type = formData.value.updates.task_type;
  }
  if (formData.value.updates.cron_expression !== undefined) {
    updates.cron_expression = formData.value.updates.cron_expression;
  }

  // 如果设置了 cron_expression，必须启用 schedule_enabled
  if (updates.cron_expression && updates.schedule_enabled === false) {
    ElMessage.warning("设置 Cron 表达式时必须启用调度开关");
    return;
  }

  updating.value = true;
  try {
    const taskIds = props.selectedTasks.map((task: any) => task.id);
    const result = await batchUpdateTasks({
      task_ids: taskIds,
      updates,
      updated_by: formData.value.updated_by,
    });

    batchResult.value = result.data;

    if (result.data.failed_count === 0) {
      ElMessage.success(
        `批量更新成功！共更新 ${result.data.success_count} 个任务`
      );
      // 延迟关闭弹窗，让用户看到结果
      setTimeout(() => {
        emit("confirm", result.data);
        visible.value = false;
      }, 2000);
    } else {
      ElMessage.warning(
        `部分更新成功：成功 ${result.data.success_count} 个，失败 ${result.data.failed_count} 个`
      );
    }
  } catch (error: any) {
    ElMessage.error(error?.message || "批量更新失败");
  } finally {
    updating.value = false;
  }
};

// 取消
const handleCancel = () => {
  visible.value = false;
};
</script>

<style scoped lang="scss">
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}
</style>
